package com.lw.extraceim.ui.activity.base;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.lw.extraceim.R;
import com.lw.extraceim.app.ExtraceApplication;
import com.lw.extraceim.ui.activity.LoginActivity;

import java.util.List;

/**
 * @Author : liwei
 * @Email : 1759840027@qq.com
 * @Description : 自定义的Activity类
 * @Date : 2019/4/11 10:58
 */
public abstract class BaseActivity extends AppCompatActivity {

    private static final String TAG = "BaseActivity";

    private long exitTime = 0; //两次点击返回键的间隔时间
    protected ExtraceApplication application; // 全局application
    public boolean isLoginOrRegist = false; //判断是否登录或者注册界面
    protected AlertDialog.Builder dialog;//提示框
//    protected ActionBar actionBar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        application = (ExtraceApplication) getApplication();
        application.addActivity(this);
//        actionBar = getSupportActionBar();
//        actionBar.setDisplayHomeAsUpEnabled(true);

        // checkLogin(); //检查用户是否登录
        initView();//初始化界面组件
        initData();//初始化数据
        initEvent();//初始化当前界面的事件
        refreshUI();//刷新界面
    }

    /**
     * 初始化界面
     */
    public abstract void initView();

    /**
     * 初始化数据
     */
    public abstract void initData();

    /**
     * 刷新界面
     */
    public abstract void refreshUI();

    /**
     * 初始化时间
     */
    public abstract void initEvent();

    /**
     * 检查用户是否登录 如果未登录则跳转到登录界面
     * 登录和注册界面不用检查
     */
    public void checkLogin() {
        if (application.getUserInfo() == null && !isLoginOrRegist) {
            Toast.makeText(this, "你还未登录！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            exit();
//            return false;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @Override
    public void onBackPressed() {
        exit();
    }

    @Override
    public void finish() {
        application.removeActivity(this);
        super.finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        FragmentManager fragmentManager = getSupportFragmentManager();
        for (int indext = 0; indext < fragmentManager.getFragments().size(); indext++) {
            Fragment fragment = fragmentManager.getFragments().get(indext); //找到第一层Fragment
            if (fragment == null)
                Log.w(TAG, "Activity result no fragment exists for index: 0x"
                        + Integer.toHexString(requestCode));
            else
                handleResult(fragment, requestCode, resultCode, data);
        }
    }

    /**
     * 递归调用，对所有的子Fragment生效
     *
     * @param fragment
     * @param requestCode
     * @param resultCode
     * @param data
     */
    private void handleResult(Fragment fragment, int requestCode, int resultCode, Intent data) {
        fragment.onActivityResult(requestCode, resultCode, data);//调用每个Fragment的onActivityResult
        Log.e(TAG, "MyBaseFragmentActivity");
        List<Fragment> childFragment = fragment.getChildFragmentManager().getFragments(); //找到第二层Fragment
        if (childFragment != null)
            for (Fragment f : childFragment)
                if (f != null) {
                    handleResult(f, requestCode, resultCode, data);
                }
        if (childFragment == null)
            Log.e(TAG, "MyBaseFragmentActivity1111");
    }

    /**
     * '
     * 退出按钮退出app，并finish所有activity
     */
    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(), "再按一次退出程序",
                    Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            application.exitApp(); //退出app
            System.exit(0);
        }
    }


    /**
     * 隐藏软键盘(只适用于Activity，不适用于Fragment)
     */
    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    //显示提示框
    public void showDialog(String title, String message, String positiveButtonStr,
                           String negativeButtonstr,
                           DialogInterface.OnClickListener positiveListener,
                           DialogInterface.OnClickListener negativeListener) {
        dialog = new AlertDialog.Builder(this);
        dialog.setTitle(title);
        dialog.setMessage(message);
        dialog.setPositiveButton(positiveButtonStr, positiveListener);
        dialog.setNegativeButton(negativeButtonstr, negativeListener);
        dialog.show();
    }

    /**
     * 显示提示框
     *
     * @param message
     * @return
     */
    public void alert(String message) {
        showDialog("提示", message, "确定", null, null, null);
    }

    /**
     * 显示 Toast
     *
     * @param message
     */
    public void toast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * 启动条形码扫描
     *
     * @param activity
     * @param captureActivity
     * @param prompt
     * @param requestCode
     */
    public void startQRScan(Activity activity, Class captureActivity,
                            String prompt, int requestCode) {
        IntentIntegrator intentIntegrator = new IntentIntegrator(activity);
        intentIntegrator.setCaptureActivity(captureActivity);
        intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
        intentIntegrator.setPrompt(prompt);
        //设置请求码
        intentIntegrator.setRequestCode(requestCode);
        application.setScanActivityRequestCode(requestCode);

        intentIntegrator.setBeepEnabled(true);
        intentIntegrator.setBarcodeImageEnabled(true);
        intentIntegrator.initiateScan();
    }

}

